#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2018/1/13 0013 19:37
# @Author  : Arliki
# @File    : distribut_1.py

# 分布式进程
# →→→!!{服务进程，负责启动queue，注册，写入任务}!!←←←
# →→→!!{必须以入口文件启动}!!←←←
import random, time  # not important
import queue
from multiprocessing.managers import BaseManager

# 发送任务的队列
send_queue = queue.Queue()


def return_send():
    global send_queue
    return send_queue


# 接收结果的队列
receive_queue = queue.Queue()


def return_receive():
    global receive_queue
    return receive_queue


# 继承BaseManager
class Distribut(BaseManager):
    pass


# →→→!!{需要用if哪个启动  目测}!!←←←
def run():
    # 注册到网络 callable关联了queue对象
    Distribut.register('get_send_queue', callable=return_send)
    Distribut.register('get_receive_queue', callable=return_receive)
    # 绑定端口 5000 验证码abcd
    manager = Distribut(address=('127.0.0.1', 8888), authkey=b'abcd')

    # 启动queue
    manager.start()
    # 获取通过网络访问的queue对象
    send = manager.get_send_queue()
    receive = manager.get_receive_queue()
    # 放入任务
    # time.sleep(11)
    for i in range(20):
        n = random.randint(1, 999)
        print('send key %d...' % n)
        send.put(n)
    # 从receive读取结果
    print('get receive from workers begin...')
    for i in range(200):
        try:
            r = receive.get(timeout=10)
            if r == 'send is empty':
                print('no data receive,will be exit')
                manager.shutdown()
                time.sleep(3)
                print('manager exit')
                exit()
            else:
                print('receive : %s' % r)
        except queue.Empty:
            print('worker is die')
            exit()
    # 关闭
    manager.shutdown()
    print('manager exit')


if __name__ == '__main__':
    run()
